本次範例以 exchangerate-api 為例,需要先註冊信箱並有 key 才可以使用。
以 Net:HTTP Ruby 內建 Library 為例
uri = URI('http://example.com/some_path?query=string')
Net::HTTP.start(uri.host, uri.port) do |http|
request = Net::HTTP::Get.new uri
response = http.request request # Net::HTTPResponse object
end
uri = URI('http://example.com/cached_response')
file = File.stat 'cached_response'
req = Net::HTTP::Get.new(uri)
req['If-Modified-Since'] = file.mtime.rfc2822
註: 詳細可參考 https://ruby-doc.org/stdlib-3.0.2/libdoc/net/http/rdoc/Net/HTTP.html
接下來,我們用 exchangerate 匯率交易的 api,以最新的美金匯率換算為例,EXCHANGE_RATE_APP_ID
設定在環境變數內,為 exchangerate-api 提供的 secret_key(別直接寫在 code 內 commit 惹~)
另外也可以將連結放入前幾篇介紹的 config 內,這邊的 Settings.exchange_rates_api
,也就是 "https://v6.exchangerate-api.com/v6"
,透過 GET 得到 API response。
uri = URI(Settings.exchange_rates_api + "/#{ENV["EXCHANGE_RATE_APP_ID"]}/latest/USD")
Net::HTTP.start(uri.host, uri.port, use_ssl: true) do |http|
req = Net::HTTP::Get.new uri.request_uri
res = http.request(req)
end
就馬上可以獲得 exchange_rate 啦!
{
"result": "success",
"documentation": "https://www.exchangerate-api.com/docs",
"terms_of_use": "https://www.exchangerate-api.com/terms",
"time_last_update_unix": 1634169602,
"time_last_update_utc": "Thu, 14 Oct 2021 00:00:02 +0000",
"time_next_update_unix": 1634256002,
"time_next_update_utc": "Fri, 15 Oct 2021 00:00:02 +0000",
"base_code": "USD",
"conversion_rates": {
"USD": 1,
"AED": 3.6725,
"AFN": 84.9745,
"ALL": 105.0810,
"AMD": 478.1197,
"ANG": 1.7900,
"AOA": 601.0158,
"ARS": 98.9610,
"AUD": 1.3572,
"AWG": 1.7900,
"AZN": 1.6973,
"BAM": 1.6887,
"BBD": 2.0000,
"BDT": 85.5464,
"BGN": 1.6896,
"BHD": 0.3760,
"BIF": 1983.1474,
"BMD": 1.0000,
"BND": 1.3523,
"BOB": 6.8897,
"BRL": 5.5301,
"BSD": 1.0000,
#...
}
}
另外也可以先透過 Postman 來打試試看,只要直接將網址丟在上方即可馬上獲得。